package com.zmjmall.demo.api.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.zmjmall.demo.api.UserService;
import com.zmjmall.demo.dao.UserMapper;
import com.zmjmall.demo.dto.LoginPasswordDTO;
import com.zmjmall.demo.model.User;
import com.zmjmall.demo.repository.UserRepository;
import com.zmjmall.demo.util.MD5Util;
import com.zmjmall.demo.util.RandomUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author zmj
 * @version 2018/7/3
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserMapper userMapper;

    @Override
    public User getByPhone(String phone) {
        return userRepository.findByPhone(phone);
    }

    @Override
    public User toLogin(User user) {
        return userMapper.toLogin();
    }

    @Override
    @Transactional
    public void updateLoginInfo(User user) {
        userMapper.updateLoginInfo(user);
    }

    @Override
    @Transactional
    public boolean insert(User user) {
        User byPhone = userRepository.findByPhone(user.getPhone());
        //密码加盐,前台传入密码为的为md5后的
        if(byPhone == null) {
            //生成6位的随机salt
            String dbSalt = RandomUtils.generateString(6);
            //根据随机盐生成入库密码
            String dbPassword = MD5Util.formPassToDBPass(user.getPassword(), dbSalt);
            user.setPassword(dbPassword);
            user.setSalt(dbSalt);
            user.setLoginCount(1);
            user.setId(IdWorker.getIdStr());
            return userMapper.insert(user) == 1? true:false;
        }
        return false;
    }

    @Override
    public boolean updateUserInfo(User user) {
        return userMapper.updateByPrimaryKeySelective(user) == 1? true:false;
    }

    @Override
    public User loginByPssword(LoginPasswordDTO loginPasswordDTO) {
        User byPhone = userRepository.findByPhone(loginPasswordDTO.getPhone());
        if(null != byPhone) {
            String dbPassword = MD5Util.formPassToDBPass(loginPasswordDTO.getPassword(), byPhone.getSalt());
            if (dbPassword.equals(byPhone.getPassword())) {
                return byPhone;
            }
        }
        return null;
    }
    @Override
    public User getUser(User user) {
        return userMapper.getUser(user);
    }
}
